package com.example.mybatis.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;

import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 使用拦截器动态替换表名
 */
//@Configuration
public class MybatisPlusConfig {

//    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
        dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
            // 获取参数方法
            Map<String, String> paramMap = RequestDataHelper.getRequestData();
            AtomicReference<String> dynamicTableName = new AtomicReference<>(tableName);
            if (paramMap != null) {
                paramMap.forEach((k, v) -> {
                    dynamicTableName.set(tableName.replace("[" + k + "]", v));
                });
            }

            return dynamicTableName.get();
        });
        interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);
        // 3.4.3.2 作废该方式
        //dynamicTableNameInnerInterceptor.setTableNameHandler();
        return interceptor;
    }
}
